<template>
  <div  class='login_bg'>
      <div  class='login_box_bg'>
          <h2  class='color-white text-center  mb28'>欢迎登录供应链管理系统</h2> 
          <a-row  style='width: 400px;margin:60px auto 0;'>
              <a-tabs v-model='currentTab'>
                <a-tab-pane tab="账户登录" key="1">
                    <a-form  v-if='currentTab==1'
                        id="components-form-demo-normal-login"
                        :form="form"
                        class="login-form"
                        @submit="handleSubmit" 
                         >
                        <a-form-item  label='用户名'  :label-col="{ span: 6 }" :wrapper-col="{ span: 14 }">
                            <a-input  v-decorator="[ 'loginName', { rules: [{ required: true, message: '请输入用户名!' },{ whitespace : true ,message:'请勿输入空格'}]} ]" placeholder="用户名"  />  
                        </a-form-item>
                        <a-form-item  label='密码'  :label-col="{ span: 6 }" :wrapper-col="{ span: 14 }">
                            <a-input v-decorator="[ 'password', { rules: [{ required: true, message: '请输入密码!' },{ whitespace : true ,message:'请勿输入空格'}]} ]" type="password" placeholder="密码"   />  
                        </a-form-item>

                        <a-form-item  style='text-align: center;' >
                            <a-button  :loading='btnLoading'  type="primary" html-type="submit" style='width: 120px;background: #105DCE' size='large'>
                                登录
                            </a-button>
                            <span class='link fr'><router-link  to='/register'>立即注册</router-link></span> 
                        </a-form-item>
                        <span></span>
                    </a-form>
                </a-tab-pane>
                <a-tab-pane tab="手机验证码登陆" key="2" >
                    <a-form  v-if='currentTab==2'
                        id="components-form-demo-normal-login"
                        :form="form"
                        class="login-form"
                        @submit="handleSubmit" 
                         >
                        <a-form-item  label='手机号'  :label-col="{ span: 6 }" :wrapper-col="{ span: 14 }">
                            <a-input  v-decorator="[ 'mobile', { rules: [{ required: true, message: '请输入手机号' },{ whitespace : true ,message:'请勿输入空格'}]} ]" placeholder="手机号"  />  
                        </a-form-item>
                        <a-form-item label="图形验证码" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }" >
                            <a-input placeholder="请输入"  v-decorator="[ 'captchaCode', { rules: [{ required: true, message: '请输入验证码' },{ whitespace : true ,message:'请勿输入空格'}]}]"  style='width: 120px;margin-right: 20px;'  @change='Re_verifyCode'/>
                            <img :src='captchaImg' alt='图形验证码'  height="40"  class='cursor mr20'  @click='change_captchaImg()'>  
                        </a-form-item> 
                        <a-form-item label="手机验证码" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
                            <a-input placeholder="请输入"  v-decorator="['verifyCode',{ rules: [{ required: true, message: '请输入验证码' }]}]" style='width: 120px;margin-right: 20px;' /> 
                            <a-button class='mr20' :disabled='verifyCode_disabled'  @click='get_verifyCode()' ><span v-if='Re_verifyCode_status'>{{reciprocal}}s后重新获取</span><span v-else>获取验证码</span></a-button>
                             
                        </a-form-item>

                        <a-form-item  style='text-align: center;'> <!-- background: #105DCE -->
                          <a-button  :loading='btnLoading'  type="primary"  html-type="submit"  style='width: 120px;background: #105DCE'  size='large' >
                              登录
                          </a-button>
                          <span class='link fr'><router-link  to='/register'>立即注册</router-link></span> 
                        </a-form-item>
                        <span></span>
                    </a-form>
                </a-tab-pane> 
              </a-tabs>
          </a-row> 
      </div>
  </div>
</template>

<script>
import { login,get_entCode_by_user,login_from_mobile }  from  '@/api/login/index'
import { getVerifyCode }  from  '@/api/common'
export default {
  name: 'login',
  data () {
    return {
      btnLoading:false,/*登录按钮等待加载*/

      currentTab:'1',
      captchaImg:'',
      captchaCode:'',//图形验证码 v-model for_require_mobileCode
      random:null,//获取图片验证码 和短信验证码 的同一随机数 
      verifyCode_disabled:true,
      Re_verifyCode_status:false,//验证码获取状态 是否正在获取中
      reciprocal:60,//30s后重新获取
 
    }
  },
  beforeCreate () {
    this.form = this.$form.createForm(this);
  },
  created(){
    this.change_captchaImg()
  },
  methods:{
    //submit
    handleSubmit (e) {
      e.preventDefault();
      let url=''
      this.form.validateFields((err, values) => {
        if (!err) {
          // console.log('Received values of form: ', values);
          this.btnLoading = true
          if(this.currentTab==1){
              login(values).then((response)=>{
                  this.commonLogin(response) 
              })
              .catch(error=>{//response执行有错误 
                  this.btnLoading = false
              })
          }
          if(this.currentTab==2){ 
              login_from_mobile(values).then((response)=>{
                  this.commonLogin(response) 
              })
              .catch(error=>{//response执行有错误 
                  this.btnLoading = false
              })
          }
        }
      });
    },
    commonLogin(response){
      let that = this
      this.$message.success('登录成功')

      //token_save - sessionStorage
      sessionStorage.setItem( 'token', response.data.token )
      sessionStorage.setItem( 'routers', JSON.stringify( response.data.routers ) )
      sessionStorage.setItem( 'currentUser', JSON.stringify({ name : response.data.username }) )
      sessionStorage.setItem( 'tokenId', response.data.tokenId )
      //token_save - vuex  /**vuex响应所有用到这个数据的组件  sessStorage 存不动值**/
      that.$store.commit( "setusername",response.data.username );
      //entCode_save -vuex 
      this.get_entCode(response.data.userCode)//企业用户登录时获取企业code

      /*初始化路由*/
      this.initIndexRouter()
      let redirect = decodeURIComponent(
          this.$route.query.redirect || "/home/tendency"
      )// console.log(redirect)
      this.$router.push(redirect);

      this.btnLoading = false
    },
    /*初始化首页路由*/
    initIndexRouter(){
        let indexRouter = {
          path: '/',
          name: "homeIndex",
          component:()=>import('@/views/home/index'),
          children: [
            ...this.generateChildRouters()
          ]
        }
        this.$router.addRoutes([indexRouter])
    },
    /*生成嵌套路由（子路由）*/
    generateChildRouters(){
        let that = this
        let childRouters = [], /*子路由数组，最后由函数return*/
            items = [],        /*左侧菜单*/
            button_limit = []  /*初始化按钮访问权限*/
            
        //如果还没有创建 需要返回一个空对象，否则会报错 Cannot convert undefined or null to object ：children数组中存的值不能为undefined
        if (!window.sessionStorage.getItem('routers')) {
            return {}
        }

        let routers = JSON.parse(sessionStorage.getItem('routers')) 
        for(let router of routers) {
            try {
                /*route-component_save*/
                if(router.isRouter == '1'  ){ 
                    let routeObj = JSON.parse(router.routerCode)
                    let component = routeObj.component.slice(1)//将路径拆解成 '@/' + ... 
                    let childRouter = {
                        path: routeObj.path,
                        name: routeObj.name,
                        component:resolve => require(['@/' + component], resolve), 
                        meta: routeObj.meta
                    }
                    // console.log(childRouter)
                    childRouters.push(childRouter) 
                }
                /*leftMenu_save*/
                if(router.isMenu == '1'){ 
                    /*一级目录*/
                    if(router.parentId == 1){
                        let routeObj = router.routerCode? JSON.parse(router.routerCode):{path:"/1"} 
                        let item = {
                                id: router.id,
                                parentId:router.parentId,
                                name: router.name,
                                icon:router.icon,
                                to: routeObj.path ,
                                sort:router.sort,
                              }
                        items.push(item)
                    }
                }
                /*btn_limit_save*/
                if(router.isMenu == '0'){ 
                    // button_limit.push(router)
                }
            }catch (ex) {
                console.warn(ex.message)
            }
        }  

        this.treeLeftNavChild(items,routers)/*二级菜单*/ 
        // that.$store.commit("setbutton_limit",button_limit);
        // console.log(childRouters)
        return childRouters
    },
    treeLeftNavChild(arr,routers){
        //alreadySavedMenu
        arr.forEach((item)=>{ 
            let child= []
            routers.forEach((it)=>{
                if(it.isMenu == '1' ){
                    if(item.id == it.parentId ){  
                        let routeObj = it.routerCode? JSON.parse(it.routerCode):{path:"/1"}  
                        child.push({
                            id: it.id,
                            parentId:it.parentId,
                            name: it.name,
                            icon:it.icon,
                            to: routeObj.path,
                            sort:it.sort,
                          })  
                    }
                }
            })
            if(child.length>=0){
                item.children=child
            }
        })

        function sortBy(a,b){
            return  a.sort - b.sort
        }
        let menu = arr.sort(sortBy)
        // console.log(menu)
        this.$store.commit("setmenudata",menu);
    },
    //entCode_save -vuex 
    get_entCode(userCode){
        get_entCode_by_user(userCode).then((res)=>{
          if(res.data.flag == true){
            this.$store.commit("setentCode",res.data.data.entCode);
          }
        })
    },

    //get_captchaImg
    change_captchaImg(){   
      this.random = Math.random()
      this.captchaImg = process.env.BASE_API+'/verify/get_captcha?requestCode='+this.random
    },
    //get_verifyCode
    get_verifyCode(){
      this.verifyCode_disabled = true

      let mobile = this.form.getFieldValue('mobile')
      let captchaCode = this.form.getFieldValue('captchaCode')
      getVerifyCode(mobile,2,captchaCode,this.random).then((res)=>{
        if(res.data.flag == true){
          this.$message.success(res.data.msg) 
          this.Re_verifyCode_status = true
          let num =  setInterval(()=>{ 
            this.reciprocal-- 
            if(this.reciprocal<=0){
              clearInterval(num)
              this.reciprocal=60
              this.Re_verifyCode_status = false
              this.Re_verifyCode()
            } 
          },1000)
        }
        else{
          this.verifyCode_disabled = false
        }
      }).catch((error)=>{
        // console.log(error)
        this.verifyCode_disabled = false
      })
    },
    //手机验证码 （手机号 图形验证码都填写时显示）
    Re_verifyCode(){ 
      let mobile = this.form.getFieldValue('mobile') 
      let captchaCode = this.form.getFieldValue('captchaCode') 
      if(mobile && captchaCode!=''){
          this.verifyCode_disabled = this.Re_verifyCode_status==false? false:true 
      }
      else{
          this.verifyCode_disabled =  true
      } 
    }, 
    
  },
  computed:{
    
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.login_bg{background: url(../../assets/img/login_bg.jpg) no-repeat center;height: 100%;padding-top:200px;}
.login_box_bg{width: 600px;margin:0 auto;padding:36px 0;background: url(../../assets/img/login_box_bg.png) no-repeat top center;background-color: #fff;}

#components-form-demo-normal-login .login-form {
  max-width: 300px;
}
#components-form-demo-normal-login .login-form-forgot {
  float: right;
}
#components-form-demo-normal-login .login-form-button {
  width: 100%;
}

</style>
